// 仓库管理Vuex模块
import { 
  contractApi, 
  materialApi, 
  warehouseApi, 
  stockInApi, 
  scanApi, 
  inventoryApi 
} from '@/api/warehouse/index'

const state = {
  // 合同相关
  contracts: [],
  contractDetail: null,
  contractMaterials: [],
  contractPagination: {
    page: 1,
    size: 20,
    total: 0
  },
  
  // 物料相关
  materials: [],
  materialDetail: null,
  materialPagination: {
    page: 1,
    size: 20,
    total: 0
  },
  
  // 仓库相关
  warehouses: [
    { code: 'RM', name: '原辅料仓库', type: 'raw_material' },
    { code: 'HW', name: '五金仓库', type: 'hardware' },
    { code: 'SP', name: '备件仓库', type: 'spare_parts' }
  ],
  
  // 入库申请相关
  stockInList: [],
  stockInDetail: null,
  stockInPagination: {
    page: 1,
    size: 20,
    total: 0
  },
  
  // 库存相关
  inventoryList: [],
  inventoryStats: null,
  inventoryPagination: {
    page: 1,
    size: 50,
    total: 0
  },
  
  // 临时选择数据
  selectedContract: null,
  selectedMaterials: [],
  
  // 加载状态
  loading: {
    contracts: false,
    materials: false,
    stockIn: false,
    inventory: false
  },
  
  // 错误信息
  error: null
}

const mutations = {
  // 合同相关mutations
  SET_CONTRACTS(state, { list, pagination }) {
    state.contracts = list
    state.contractPagination = { ...state.contractPagination, ...pagination }
  },
  
  SET_CONTRACT_DETAIL(state, detail) {
    state.contractDetail = detail
  },
  
  SET_CONTRACT_MATERIALS(state, materials) {
    state.contractMaterials = materials
  },
  
  // 物料相关mutations
  SET_MATERIALS(state, { list, pagination }) {
    state.materials = list
    state.materialPagination = { ...state.materialPagination, ...pagination }
  },
  
  SET_MATERIAL_DETAIL(state, detail) {
    state.materialDetail = detail
  },
  
  // 入库申请相关mutations
  SET_STOCK_IN_LIST(state, { list, pagination }) {
    state.stockInList = list
    state.stockInPagination = { ...state.stockInPagination, ...pagination }
  },
  
  SET_STOCK_IN_DETAIL(state, detail) {
    state.stockInDetail = detail
  },
  
  ADD_STOCK_IN(state, stockIn) {
    state.stockInList.unshift(stockIn)
  },
  
  UPDATE_STOCK_IN(state, updatedStockIn) {
    const index = state.stockInList.findIndex(item => item.id === updatedStockIn.id)
    if (index !== -1) {
      state.stockInList.splice(index, 1, updatedStockIn)
    }
  },
  
  REMOVE_STOCK_IN(state, id) {
    state.stockInList = state.stockInList.filter(item => item.id !== id)
  },
  
  // 库存相关mutations
  SET_INVENTORY_LIST(state, { list, pagination }) {
    state.inventoryList = list
    state.inventoryPagination = { ...state.inventoryPagination, ...pagination }
  },
  
  SET_INVENTORY_STATS(state, stats) {
    state.inventoryStats = stats
  },
  
  // 临时选择数据mutations
  SET_SELECTED_CONTRACT(state, contract) {
    state.selectedContract = contract
  },
  
  SET_SELECTED_MATERIALS(state, materials) {
    state.selectedMaterials = materials
  },
  
  ADD_SELECTED_MATERIAL(state, material) {
    const exists = state.selectedMaterials.find(m => m.code === material.code)
    if (!exists) {
      state.selectedMaterials.push(material)
    }
  },
  
  REMOVE_SELECTED_MATERIAL(state, materialCode) {
    state.selectedMaterials = state.selectedMaterials.filter(m => m.code !== materialCode)
  },
  
  CLEAR_SELECTED_DATA(state) {
    state.selectedContract = null
    state.selectedMaterials = []
  },
  
  // 加载状态mutations
  SET_LOADING(state, { key, value }) {
    state.loading = { ...state.loading, [key]: value }
  },
  
  SET_ERROR(state, error) {
    state.error = error
  },
  
  CLEAR_ERROR(state) {
    state.error = null
  }
}

const actions = {
  // 合同相关actions
  async fetchContracts({ commit }, params = {}) {
    commit('SET_LOADING', { key: 'contracts', value: true })
    commit('CLEAR_ERROR')
    
    try {
      const response = await contractApi.getContractList(params)
      commit('SET_CONTRACTS', {
        list: response.data.records || response.data,
        pagination: {
          page: response.data.current || 1,
          size: response.data.size || 20,
          total: response.data.total || response.data.length
        }
      })
      return response.data
    } catch (error) {
      commit('SET_ERROR', error.message)
      throw error
    } finally {
      commit('SET_LOADING', { key: 'contracts', value: false })
    }
  },
  
  async fetchContractDetail({ commit }, contractCode) {
    commit('SET_LOADING', { key: 'contracts', value: true })
    commit('CLEAR_ERROR')
    
    try {
      const response = await contractApi.getContractDetail(contractCode)
      commit('SET_CONTRACT_DETAIL', response.data)
      return response.data
    } catch (error) {
      commit('SET_ERROR', error.message)
      throw error
    } finally {
      commit('SET_LOADING', { key: 'contracts', value: false })
    }
  },
  
  async fetchContractMaterials({ commit }, contractCode) {
    commit('SET_LOADING', { key: 'materials', value: true })
    commit('CLEAR_ERROR')
    
    try {
      const response = await contractApi.getContractMaterials(contractCode)
      commit('SET_CONTRACT_MATERIALS', response.data)
      return response.data
    } catch (error) {
      commit('SET_ERROR', error.message)
      throw error
    } finally {
      commit('SET_LOADING', { key: 'materials', value: false })
    }
  },
  
  // 物料相关actions
  async fetchMaterials({ commit }, params = {}) {
    commit('SET_LOADING', { key: 'materials', value: true })
    commit('CLEAR_ERROR')
    
    try {
      const response = await materialApi.getMaterialList(params)
      commit('SET_MATERIALS', {
        list: response.data.records || response.data,
        pagination: {
          page: response.data.current || 1,
          size: response.data.size || 20,
          total: response.data.total || response.data.length
        }
      })
      return response.data
    } catch (error) {
      commit('SET_ERROR', error.message)
      throw error
    } finally {
      commit('SET_LOADING', { key: 'materials', value: false })
    }
  },
  
  async fetchMaterialDetail({ commit }, materialCode) {
    commit('SET_LOADING', { key: 'materials', value: true })
    commit('CLEAR_ERROR')
    
    try {
      const response = await materialApi.getMaterialDetail(materialCode)
      commit('SET_MATERIAL_DETAIL', response.data)
      return response.data
    } catch (error) {
      commit('SET_ERROR', error.message)
      throw error
    } finally {
      commit('SET_LOADING', { key: 'materials', value: false })
    }
  },
  
  async searchMaterials({ commit }, keyword) {
    commit('SET_LOADING', { key: 'materials', value: true })
    commit('CLEAR_ERROR')
    
    try {
      const response = await materialApi.searchMaterials(keyword)
      return response.data
    } catch (error) {
      commit('SET_ERROR', error.message)
      throw error
    } finally {
      commit('SET_LOADING', { key: 'materials', value: false })
    }
  },
  
  // 入库申请相关actions
  async fetchStockInList({ commit }, params = {}) {
    commit('SET_LOADING', { key: 'stockIn', value: true })
    commit('CLEAR_ERROR')
    
    try {
      const response = await stockInApi.getStockInList(params)
      commit('SET_STOCK_IN_LIST', {
        list: response.data.records || response.data,
        pagination: {
          page: response.data.current || 1,
          size: response.data.size || 20,
          total: response.data.total || response.data.length
        }
      })
      return response.data
    } catch (error) {
      commit('SET_ERROR', error.message)
      throw error
    } finally {
      commit('SET_LOADING', { key: 'stockIn', value: false })
    }
  },
  
  async fetchStockInDetail({ commit }, id) {
    commit('SET_LOADING', { key: 'stockIn', value: true })
    commit('CLEAR_ERROR')
    
    try {
      const response = await stockInApi.getStockInDetail(id)
      commit('SET_STOCK_IN_DETAIL', response.data)
      return response.data
    } catch (error) {
      commit('SET_ERROR', error.message)
      throw error
    } finally {
      commit('SET_LOADING', { key: 'stockIn', value: false })
    }
  },
  
  async createStockIn({ commit }, data) {
    commit('SET_LOADING', { key: 'stockIn', value: true })
    commit('CLEAR_ERROR')
    
    try {
      const response = await stockInApi.createStockIn(data)
      commit('ADD_STOCK_IN', response.data)
      return response.data
    } catch (error) {
      commit('SET_ERROR', error.message)
      throw error
    } finally {
      commit('SET_LOADING', { key: 'stockIn', value: false })
    }
  },
  
  async updateStockIn({ commit }, { id, data }) {
    commit('SET_LOADING', { key: 'stockIn', value: true })
    commit('CLEAR_ERROR')
    
    try {
      const response = await stockInApi.updateStockIn(id, data)
      commit('UPDATE_STOCK_IN', response.data)
      return response.data
    } catch (error) {
      commit('SET_ERROR', error.message)
      throw error
    } finally {
      commit('SET_LOADING', { key: 'stockIn', value: false })
    }
  },
  
  async deleteStockIn({ commit }, id) {
    commit('SET_LOADING', { key: 'stockIn', value: true })
    commit('CLEAR_ERROR')
    
    try {
      await stockInApi.deleteStockIn(id)
      commit('REMOVE_STOCK_IN', id)
      return true
    } catch (error) {
      commit('SET_ERROR', error.message)
      throw error
    } finally {
      commit('SET_LOADING', { key: 'stockIn', value: false })
    }
  },
  
  async submitForApproval({ commit }, id) {
    commit('SET_LOADING', { key: 'stockIn', value: true })
    commit('CLEAR_ERROR')
    
    try {
      const response = await stockInApi.submitForApproval(id)
      commit('UPDATE_STOCK_IN', response.data)
      return response.data
    } catch (error) {
      commit('SET_ERROR', error.message)
      throw error
    } finally {
      commit('SET_LOADING', { key: 'stockIn', value: false })
    }
  },
  
  // 库存相关actions
  async fetchInventoryList({ commit }, params = {}) {
    commit('SET_LOADING', { key: 'inventory', value: true })
    commit('CLEAR_ERROR')
    
    try {
      const response = await inventoryApi.getInventoryList(params)
      commit('SET_INVENTORY_LIST', {
        list: response.data.records || response.data,
        pagination: {
          page: response.data.current || 1,
          size: response.data.size || 50,
          total: response.data.total || response.data.length
        }
      })
      return response.data
    } catch (error) {
      commit('SET_ERROR', error.message)
      throw error
    } finally {
      commit('SET_LOADING', { key: 'inventory', value: false })
    }
  },
  
  async fetchInventoryStats({ commit }, params = {}) {
    commit('SET_LOADING', { key: 'inventory', value: true })
    commit('CLEAR_ERROR')
    
    try {
      const response = await inventoryApi.getInventoryStats(params)
      commit('SET_INVENTORY_STATS', response.data)
      return response.data
    } catch (error) {
      commit('SET_ERROR', error.message)
      throw error
    } finally {
      commit('SET_LOADING', { key: 'inventory', value: false })
    }
  },
  
  // 扫码相关actions
  async parseBatchCode({ commit }, code) {
    try {
      const response = await scanApi.parseBatchCode(code)
      return response.data
    } catch (error) {
      commit('SET_ERROR', error.message)
      throw error
    }
  },
  
  async parseWeightCode({ commit }, code) {
    try {
      const response = await scanApi.parseWeightCode(code)
      return response.data
    } catch (error) {
      commit('SET_ERROR', error.message)
      throw error
    }
  },
  
  async validateBatchNo({ commit }, batchNo) {
    try {
      const response = await scanApi.validateBatchNo(batchNo)
      return response.data
    } catch (error) {
      commit('SET_ERROR', error.message)
      throw error
    }
  },
  
  // 选择数据相关actions
  selectContract({ commit }, contract) {
    commit('SET_SELECTED_CONTRACT', contract)
  },
  
  selectMaterials({ commit }, materials) {
    commit('SET_SELECTED_MATERIALS', materials)
  },
  
  addSelectedMaterial({ commit }, material) {
    commit('ADD_SELECTED_MATERIAL', material)
  },
  
  removeSelectedMaterial({ commit }, materialCode) {
    commit('REMOVE_SELECTED_MATERIAL', materialCode)
  },
  
  clearSelectedData({ commit }) {
    commit('CLEAR_SELECTED_DATA')
  }
}

const getters = {
  // 合同相关getters
  contractByCode: (state) => (code) => {
    return state.contracts.find(contract => contract.code === code)
  },
  
  activeContracts: (state) => {
    return state.contracts.filter(contract => contract.status === 'active')
  },
  
  // 物料相关getters
  materialByCode: (state) => (code) => {
    return state.materials.find(material => material.code === code)
  },
  
  materialsByCategory: (state) => (category) => {
    return state.materials.filter(material => material.category === category)
  },
  
  // 入库申请相关getters
  stockInByStatus: (state) => (status) => {
    return state.stockInList.filter(item => item.status === status)
  },
  
  pendingStockIn: (state) => {
    return state.stockInList.filter(item => item.status === 'pending')
  },
  
  approvedStockIn: (state) => {
    return state.stockInList.filter(item => item.status === 'approved')
  },
  
  // 库存相关getters
  inventoryByWarehouse: (state) => (warehouseCode) => {
    return state.inventoryList.filter(item => item.warehouseCode === warehouseCode)
  },
  
  lowStockItems: (state) => {
    return state.inventoryList.filter(item => item.currentStock <= item.minStock)
  },
  
  // 工具getters
  isLoading: (state) => (key) => {
    return state.loading[key] || false
  },
  
  hasError: (state) => {
    return !!state.error
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}